package cl.xintec.utils.validator
{
	import mx.validators.StringValidator;
	import mx.validators.ValidationResult;

	public class RutValidator10 extends StringValidator
	{

        // Arreglo para retornar el valor de doValidation().
        private var results:Array;

		// Constructor		
		public function RutValidator10()
		{
			super();
		}

        // Definición de doValidation().
        override protected function doValidation(value:Object):Array {

            // Limpieza de los resultados.
            results = [];

			// Validación del padre
            results = super.doValidation(value);
                    
            // Se retorna en caso de errores
            if (results.length > 0)
                return results;
        
			// Validación del RUT
			if (value == null || String(value) == "") {
				results.push(new ValidationResult(true, null, "null", 
                    "RUT nulo o vacío"));			
			  	return results;
			}
			
			var src: String = String(value);
			
			if (src.length > 15) {
				results.push(new ValidationResult(true, null, "toolong", 
                    "RUT Demasiado largo"));			
			  	return results;
			}

			var dig:int, total:int = 0;

			var index:int = src.indexOf("-");
			
			if (index < 0) {
				results.push(new ValidationResult(true, null, "sepdv", 
                    "RUT sin separador de digito verificador"));			
			  	return results;
			}
			  	
			if (index != (src.length-2)) {
				results.push(new ValidationResult(true, null, "dvToolong", 
                    "RUT incorrecto"));			
			  	return results;
			}
			
			var rut:String = src.substring(0,index);
			
			var dv:String = src.substring(index+1,index+2).toUpperCase()
			
			var j:int = 2;
			var i:int = rut.length-1;
			for (i; i>=0 ;i--) {
				dig = int(rut.substring(i, i+1));
 				if (dig < 0) {
					results.push(new ValidationResult(true, null, "dvToolong", 
	                    "RUT incorrecto"));			
				  	return results;
				}
				total += (dig*j);
				j = (j==7)?2:j+1;
			}

			var indv:int = 10 - (total % 11);
			var _dv:String = "123456789K0".substring(indv,indv+1);
			if (_dv != dv) {
				results.push(new ValidationResult(true, null, "dvToolong", 
                    "RUT incorrecto"));			
			  	return results;
			}				
            
            return results;
        }
		
	}
}